<template>
  <div>
    <GlassCard>
      <div
        style="
          margin-bottom: 8px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        ">
        <div style="display: flex; align-items: center; gap: 6px">
          <span style="font-size: 12px">默认条数</span>
          <el-input-number
            v-model="defaultCount"
            :min="1"
            :max="10"
            :step="1"
            :step-strictly="true"
            :precision="0"
            :controls="false"
            size="small"
            style="width: 72px" />
        </div>
        <el-button size="small" @click="resetRows">重置</el-button>
      </div>

      <el-table
        :data="rows"
        border
        size="small"
        style="width: 100%; font-size: 12px; border-radius: 8px">
        <!-- <el-table-column type="index" label="#" width="42" align="center" /> -->

        <el-table-column label="总价" width="100" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.total"
              :min="0"
              :step="0.01"
              :precision="2"
              :controls="false"
              class="cell-input"
              style="width: 100%" />
          </template>
        </el-table-column>

        <el-table-column label="数量" width="84" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.qty"
              :min="0"
              :step="1"
              :controls="false"
              class="cell-input"
              style="width: 100%" />
          </template>
        </el-table-column>

        <el-table-column
          label="单价"
          width="84"
          align="center"
          :sortable="true"
          :sort-method="sortByUnitPrice">
          <template #default="{ row }">
            <strong>{{ unitPriceText(row) }}</strong>
          </template>
        </el-table-column>

        <el-table-column width="42" align="center">
          <template #header>
            <el-icon><Operation /></el-icon>
          </template>
          <template #default="{ $index }">
            <el-icon style="cursor: pointer" @click="removeRow($index)"
              ><Delete
            /></el-icon>
          </template>
        </el-table-column>
      </el-table>

      <div style="padding: 8px 0">
        <el-button type="primary" style="width: 100%" @click="addRow"
          >新增一条</el-button
        >
      </div>
    </GlassCard>
  </div>
</template>

<script setup lang="ts">
import { Delete, Operation } from "@element-plus/icons-vue"
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInputNumber,
  ElTable,
  ElTableColumn
} from "element-plus"
import { onMounted, reactive, ref, watch } from "vue"

import { getFromStorage, saveToStorage } from "../scripts/storage.js"
// @ts-ignore - SFC default export by Vue plugin
import GlassCard from "./ui/GlassCard.vue"

type Row = { id: number; total: number; qty: number }

function createRow(id: number): Row {
  return { id, total: 0, qty: 0 }
}

const rows = reactive<Row[]>([createRow(1), createRow(2), createRow(3)])
const defaultCount = ref<number>(3)

function addRow() {
  const id = (rows[rows.length - 1]?.id || 0) + 1
  rows.push(createRow(id))
}

function removeRow(idx: number) {
  rows.splice(idx, 1)
}

function resetRows() {
  const count = Math.floor(
    Math.max(1, Math.min(10, Number(defaultCount.value) || 3))
  )
  const next: Row[] = []
  for (let i = 1; i <= count; i++) next.push(createRow(i))
  rows.splice(0, rows.length, ...next)
}

// Keep table length in sync with defaultCount, while preserving existing values
watch(defaultCount, (val) => {
  const target = Math.floor(Math.max(1, Math.min(10, Number(val) || 1)))
  if (defaultCount.value !== target) defaultCount.value = target
  if (target > rows.length) {
    for (let i = rows.length + 1; i <= target; i++) rows.push(createRow(i))
  } else if (target < rows.length) {
    rows.splice(target)
  }
})

// ---------- Persistence ----------
const STORAGE_KEY = "unit_price_state"

function serializeRows() {
  return rows.map((r) => ({ total: r.total, qty: r.qty }))
}

async function saveState() {
  const payload = {
    defaultCount: defaultCount.value,
    rows: serializeRows()
  }
  await saveToStorage(STORAGE_KEY, payload)
}

async function loadState() {
  try {
    const data = (await getFromStorage(STORAGE_KEY)) as any
    if (!data) return
    const dc = Math.floor(
      Math.max(1, Math.min(10, Number(data.defaultCount) || 3))
    )
    defaultCount.value = dc
    const arr = Array.isArray(data.rows) ? data.rows : []
    const next: Row[] = []
    for (let i = 0; i < Math.min(10, Math.max(dc, arr.length)); i++) {
      const it = arr[i] || { total: 0, qty: 0 }
      next.push({
        id: i + 1,
        total: Number(it.total) || 0,
        qty: Number(it.qty) || 0
      })
    }
    rows.splice(
      0,
      rows.length,
      ...(next.length ? next : [createRow(1), createRow(2), createRow(3)])
    )
  } catch (_e) {
    // ignore
  }
}

onMounted(() => {
  loadState()
})

watch(
  () => ({ dc: defaultCount.value, rows: serializeRows() }),
  () => {
    void saveState()
  },
  { deep: true }
)

const DECIMAL_PLACES = 6
function roundTo(value: number, places = DECIMAL_PLACES): number {
  const factor = 10 ** places
  return Math.round((value + Number.EPSILON) * factor) / factor
}

function unitPrice(row: Row): number | null {
  if (!row || row.qty <= 0) return null
  return roundTo(row.total / row.qty)
}

function unitPriceText(row: Row): string {
  const v = unitPrice(row)
  return v == null ? "--" : v.toFixed(4)
}

function sortByUnitPrice(a: Row, b: Row) {
  const va = unitPrice(a)
  const vb = unitPrice(b)
  const na = va == null ? Number.NEGATIVE_INFINITY : va
  const nb = vb == null ? Number.NEGATIVE_INFINITY : vb
  return na - nb
}
</script>
